package com.example.myapplication;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.myapplication.Helper.MemorandumHelper;
import com.example.myapplication.adapter.MemorandumAdapter;
import com.example.myapplication.bean.ImportBean;
import com.example.myapplication.bean.MemorandumBean;

import java.util.ArrayList;
import java.util.Calendar;


public class MemorandumActivity extends AppCompatActivity {
    private MemorandumHelper memorandumHelper;
    private SQLiteDatabase database;
    private ArrayList<MemorandumBean> dataSet = new ArrayList<MemorandumBean>();
    private MemorandumAdapter memorandumAdapter;
    private ListView listView;
    private EditText word_txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_memorandum);
        //实例化控件
        listView = findViewById(R.id.mem_list);
        word_txt = findViewById(R.id.view_select);

        //创建数据库
        memorandumHelper = new MemorandumHelper(this, "memorandum.db", null, 1);
        database = memorandumHelper.getReadableDatabase();

        //查询所有
        initdataSet();

        //展示item列表
        memorandumAdapter = new MemorandumAdapter(MemorandumActivity.this, R.layout.memorandum, dataSet);
        listView.setAdapter(memorandumAdapter);

        //单击修改
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                //实现跟新增同
                View updataview = LayoutInflater.from(MemorandumActivity.this).inflate(R.layout.activity_add, null);
                EditText nowtitle = updataview.findViewById(R.id.now_title);
                EditText nowinfor = updataview.findViewById(R.id.data_information);
                final MemorandumBean memorandumBean = dataSet.get(position);
                nowtitle.setText(memorandumBean.getTitle());
                nowinfor.setText(memorandumBean.getInfor());
                new AlertDialog.Builder(MemorandumActivity.this)
                        .setIcon(R.drawable.update)
                        .setTitle("修改备忘录")
                        .setView(updataview)
                        .setPositiveButton("修改", new DialogInterface.OnClickListener() {
                            @RequiresApi(api = Build.VERSION_CODES.M)
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                String uptitle = nowtitle.getText().toString().trim();
                                //获取时间
                                Calendar calendar = Calendar.getInstance();
                                String uptime = calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日";
                                String upinfor = nowinfor.getText().toString().trim();
                                //操作数据库
                                ContentValues values = new ContentValues();
                                values.put("title", uptitle);
                                values.put("time", uptime);
                                values.put("infor", upinfor);
                                long result = database.update("memorandum", values, "title=?", new String[]{memorandumBean.getTitle()});
                                if (result == 1) {
                                    MemorandumBean newmemorandumBean = new MemorandumBean(uptitle, uptime, upinfor);
                                    //替换原来内容，更新单行视图
                                    dataSet.set(position, newmemorandumBean);
                                    memorandumAdapter.notifyDataSetChanged();
                                    Toast.makeText(MemorandumActivity.this, "修改成功!", Toast.LENGTH_LONG).show();
                                } else {
                                    Toast.makeText(MemorandumActivity.this, "修改失败~", Toast.LENGTH_LONG).show();
                                }
                            }
                        }).setNegativeButton("再想想", null)
                        .create()
                        .show();
            }
        });

        //长单击删除事件
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
                final MemorandumBean memorandumBean = dataSet.get(position);
                new AlertDialog.Builder(MemorandumActivity.this)
                        .setIcon(R.drawable.del)
                        .setTitle("删除")
                        .setMessage("你要删除标题为" + memorandumBean.getTitle() + "的备忘录吗？")
                        .setPositiveButton("是的", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                long sql = database.delete("memorandum", "title=?", new String[]{memorandumBean.getTitle()});
                                if (sql == 1) {
                                    //删除成功
                                    dataSet.remove(position);
                                    memorandumAdapter.notifyDataSetChanged();
                                    Toast.makeText(MemorandumActivity.this, "删除成功!", Toast.LENGTH_SHORT).show();
                                } else {
                                    //删除失败
                                    Toast.makeText(MemorandumActivity.this, "删除失败~", Toast.LENGTH_SHORT).show();
                                }
                            }
                        })
                        .setNegativeButton("取消", null)
                        .create()
                        .show();
                return true;
            }
        });

    }


    //查询数据库(查询所有，进页面自动查询)
    public void initdataSet() {
        String sql = "select * from memorandum";
        Cursor cursor = database.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            MemorandumBean memorandumBean = new MemorandumBean(cursor.getString(1), cursor.getString(2), cursor.getString(3));
            dataSet.add(memorandumBean);
        }
    }


    //新增事件弹窗
    public void add_text(View view) {
        //创建对话框
        View layout = LayoutInflater.from(MemorandumActivity.this).inflate(R.layout.activity_add, null);
        EditText nowtitle = layout.findViewById(R.id.now_title);
        EditText nowinfor = layout.findViewById(R.id.data_information);
        new AlertDialog.Builder(MemorandumActivity.this)
                .setIcon(R.drawable.add)
                .setTitle("添加备忘录")
                .setView(layout)
                .setPositiveButton("添加", new DialogInterface.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.M)
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //获取时间
                        Calendar calendar = Calendar.getInstance();
                        String time = calendar.get(Calendar.YEAR) + "年" + (calendar.get(Calendar.MONTH) + 1) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日";
                        String title = nowtitle.getText().toString().trim();
                        String infor = nowinfor.getText().toString().trim();
                        //判断标题是否为空
                        if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(infor)) {
                            //不为空就存入数据库
                            ContentValues values = new ContentValues();
                            values.put("title", title);
                            values.put("time", time);
                            values.put("infor", infor);
                            long result = database.insert("memorandum", null, values);
                            if (result != -1) {
                                //添加成功
                                Toast.makeText(MemorandumActivity.this, "添加成功！", Toast.LENGTH_LONG).show();
                                //更新到列表
                                MemorandumBean newmemorandumBean = new MemorandumBean(title, time, infor);
                                dataSet.add(newmemorandumBean);
                                memorandumAdapter.notifyDataSetChanged();
                            } else {
                                //添加失败
                                Toast.makeText(MemorandumActivity.this, "添加失败~", Toast.LENGTH_LONG).show();
                            }
                        } else {
                            Toast.makeText(MemorandumActivity.this, "还没写标题/内容哦~", Toast.LENGTH_LONG).show();
                        }
                    }
                }).setNegativeButton("返回", null)
                .create()
                .show();
    }

    //模糊查询事件
    public void doFind(View view) {
        //删除原有列表
        for (int i = 0; i < dataSet.size(); i++) {
            dataSet.remove(i--);
        }
        //获取搜索框内容
        String word = word_txt.getText().toString().trim();
        //查询数据库
        String querySQL = "select * from memorandum where title like ? or time like ? or infor like ?";
        Cursor cursor = database.rawQuery(querySQL, new String[]{"%" + word + "%", "%" + word + "%", "%" + word + "%"});
        if (cursor.getCount() != 0) {
            //查询到了结果
            Toast.makeText(this, "共查询到" + cursor.getCount() + "个结果", Toast.LENGTH_SHORT).show();
            while (cursor.moveToNext()) {
                //添加到列表
                MemorandumBean memorandumBean = new MemorandumBean(cursor.getString(1), cursor.getString(2), cursor.getString(3));
                dataSet.add(memorandumBean);
            }
            // 由Adapter通知ListView更新视图
            memorandumAdapter.notifyDataSetChanged();
        } else {
            //没有收录此结果
            Toast.makeText(this, "没有搜索到关于" + word + "的结果", Toast.LENGTH_SHORT).show();
        }
    }
}
